package utils

import (
	"gopkg.in/gomail.v2"
	"sg-backend/config"
	"sg-backend/global"
	"strconv"
)

func SendMail(sendToAddress string, subject string, content string) bool {

	// 创建一个邮箱连接
	EmailPort, err := strconv.Atoi(config.Config("EMAIL_PORT"))
	if err != nil {
		global.SLog.Error("配置邮件发送端口错误，可能您填写的端口不是数字类型。邮件发送失败！%+v", err)
		return false
	}
	mailer := gomail.NewDialer(
		config.Config("EMAIL_HOST"),
		EmailPort,
		config.Config("EMAIL_USER"),
		config.Config("EMAIL_PASS"),
	)

	// 构造邮件体
	email := gomail.NewMessage()
	email.SetHeader("From", config.Config("EMAIL_USER"))
	email.SetAddressHeader("From", config.Config("EMAIL_USER"), config.Config("EMAIL_FROM_NAME"))
	email.SetHeader("To", sendToAddress)
	email.SetHeader("Subject", subject)
	email.SetBody("text/html", content)

	// 	连接服务器,发送
	if err := mailer.DialAndSend(email); err != nil {

		// 发送失败
		global.SLog.Error("给：%v 发送主题：%v 的邮件发送失败！%+v", sendToAddress, subject, err)
		return false
	}

	return true
}
